package com.ruoyi.web.controller.kaoyan;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.kaoyan.domain.EducationNews;
import com.ruoyi.kaoyan.service.EducationNewsService;
import com.ruoyi.system.service.ISysFileInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 后台考研资讯管理
 * @author admin
 */
@Api(tags = "后台考研资讯", value ="后台考研资讯" )
@RestController
@RequestMapping("/education/news")
public class EducationNewsController extends BaseController {

    @Autowired
    private EducationNewsService newsService;
    @Autowired
    private ISysFileInfoService fileInfoService;

    @ApiOperation("考研资讯列表")
    @PostMapping("/newsList")
    public AjaxResult newsList(String title){
        LambdaQueryWrapper<EducationNews> queryWrapper = new LambdaQueryWrapper<EducationNews>().like(StringUtils.isNotBlank(title), EducationNews::getTitle, title);
        Page<EducationNews> page = newsService.page(startPagePlus(), queryWrapper);
        List<EducationNews> records = page.getRecords();
        Set<String> coverSet = records.stream().map(EducationNews::getCover).collect(Collectors.toSet());
        Map<String, String> coverPathMap = fileInfoService.getFilePathMap(coverSet);
        records.forEach(e -> {
            e.setCoverPath(coverPathMap.get(e.getCover()));
        });
        return AjaxResult.ok().page(page, records).build();
    }

    @ApiOperation("新增或修改资讯")
    @PostMapping("/saveOrUpdate")
    public AjaxResult saveOrUpdate(@RequestBody EducationNews news){
        if (StringUtils.checkObjAllFieldsIsNull(news)){
            return AjaxResult.error("内容不能为空");
        }
        boolean update = newsService.saveOrUpdate(news);
        return toAjax(update);
    }

    @ApiOperation("删除资讯")
    @PostMapping("/remove")
    public AjaxResult removeById(Long id){
        boolean remove = newsService.removeById(id);
        return toAjax(remove);
    }
}
